package logger

import (
	"fmt"
	"os"

	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
)

var _logger *logger

var LoggerFile = ""

func init() {
	_logger = NewLogger(LoggerFile, 100, 3, 30)
}

func Info(args ...interface{}) {
	_logger.Info(args...)
}

func Warn(args ...interface{}) {
	_logger.Warn(args...)
}

func Error(args ...interface{}) {
	_logger.Error(args...)
}

func Debug(args ...interface{}) {
	_logger.Debug(args...)
}

func Println(args ...interface{}) {
	_logger.Info(args...)
}

func Printf(format string, args ...any) {
	buffer := fmt.Sprintf(format, args...)
	_logger.Info(buffer)
}

type logger struct {
	console *logrus.Logger
	file    *logrus.Logger
}

func NewLogger(fileName string, maxSize, maxBackups, maxAge int) *logger {
	log := logrus.New()
	file := logrus.New()

	lj := &lumberjack.Logger{
		Filename:   fileName,   // 日志文件路径
		MaxSize:    maxSize,    // 每个文件的最大尺寸（MB）
		MaxBackups: maxBackups, // 保留旧文件的最大数量
		MaxAge:     maxAge,     // 文件保留天数
		Compress:   true,       // 是否压缩旧文件
	}

	// log.SetFormatter(&logrus.TextFormatter{
	// 	DisableColors:   false,
	// 	FullTimestamp:   true,
	// 	TimestampFormat: "2006-01-02 15:04:05",
	// })

	// log.SetReportCaller(true)
	log.SetFormatter(&CustomFormatter{})

	// multiWriter := io.MultiWriter(lj, os.Stdout)
	log.SetOutput(os.Stdout)
	log.SetLevel(logrus.DebugLevel)

	// file.SetReportCaller(true)
	file.SetFormatter(&CustomFormatter{})
	file.SetOutput(lj)
	file.SetLevel(logrus.DebugLevel)

	return &logger{console: log, file: file}
}

func (l *logger) SetLevel(level logrus.Level) {
	l.console.SetLevel(level)
	l.file.SetLevel(level)
}

func (l *logger) Info(args ...interface{}) {
	l.console.Info(args...)
	l.file.Info(args...)
}

func (l *logger) Warn(args ...interface{}) {
	l.console.Warn(args...)
	l.file.Warn(args...)

}

func (l *logger) Error(args ...interface{}) {
	l.console.Error(args...)
	l.file.Error(args...)

}

func (l *logger) Debug(args ...interface{}) {
	l.console.Debug(args...)
	l.file.Debug(args...)
}
